package com.esxy.manage.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.esxy.entity.TbContent;
import com.esxy.entity.TbContentExample;
import com.esxy.manage.util.FastDfsUtil;
import com.esxy.service.TbContentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/content")
public class TbContentController {

    @Reference(interfaceClass = TbContentService.class,check = false)
    private TbContentService tbContentService;

    @Autowired
    private FastDfsUtil fastDfsUtil;

    @RequestMapping("/getContentAll")
    @ResponseBody
    public PageInfo<TbContent> getContentAll(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        // 使用PageHelper分页（注意：必须在查询方法前调用）
        PageHelper.startPage(pageNum, pageSize);
        TbContentExample example = new TbContentExample();
        List<TbContent> list = tbContentService.getContentAll(example);
        return new PageInfo<>(list);
    }

/*Multipartfile:用来文件处理
    value 匹配前端name属性的值
    required 默认为true必填，false选填*/
    @RequestMapping("/addContent")
    public String addContent(@RequestParam(value = "contentpic",required = false) MultipartFile file, TbContent tbContent){
        try {
//            图片上传到fastdfs服务器中
            byte[] bytes = file.getBytes();
//            获取文件类型
            String filename = file.getOriginalFilename();
            String substring = filename.substring(filename.lastIndexOf(".")+1);
//            获取路径
            String url = fastDfsUtil.upload_file(bytes,substring);
            //            2、保存数据到数据库中
            tbContent.setPic(url);
            int content = tbContentService.addContent(tbContent);
            if (content<=0){
                return "err";
            }else {
                return "addContent";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    //    http://192.168.190.53:80/group1/M00/00/00/wKi-NWhBtVyAJrxyAAzULdjkiSk581.jpg
    @RequestMapping("/deleteContent")
    @ResponseBody
    public String deleteContent(@RequestBody Map<String, Long> request) {
        Long id = request.get("id");
        try {
            if (id == null) {
                return "err:ID不能为空";
            }

            TbContent content = tbContentService.selectById(id);
            if (content == null) {
                return "err:找不到对应内容";
            }

            // 删除FastDFS文件
            String url = content.getPic();
            if (url != null && !url.isEmpty()) {
                int groupStart = url.indexOf("/", url.indexOf("//") + 2) + 1;
                int groupEnd = url.indexOf("/", groupStart);
                String group = url.substring(groupStart, groupEnd);
                String filePath = url.substring(groupEnd + 1);
                fastDfsUtil.delete_file(group, filePath);
            }

            // 删除数据库记录
            int result = tbContentService.deleteById(id);
            return result > 0 ? "deleteContent" : "err:数据库删除失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "err:" + e.getMessage();
        }
    }

    @RequestMapping("/getById")
    @ResponseBody
    public TbContent getById(Long id){
        TbContent data = tbContentService.selectById(id);
        return data;
    }

    @RequestMapping("/updateContent")
    @ResponseBody
    public String updateContent(@RequestParam(value = "contentpic",required = false) MultipartFile file, TbContent newTbContent) throws IOException {
//        根据前端传回的新数据查找旧的数据
        TbContent oldTbContent = getById(newTbContent.getId());
//        判断新的pic是否为null
        if (file == null || file.isEmpty()) {
//            未更改则直接把图片旧地址赋给新的值
            newTbContent.setPic(oldTbContent.getPic());
        } else {
//            更改则删除旧照片
            String url1 = oldTbContent.getPic();
            int groupStart = url1.indexOf("/", url1.indexOf("//") + 2) + 1; // 定位到第一个 "/" 之后
            int groupEnd = url1.indexOf("/", groupStart);
            String group = url1.substring(groupStart, groupEnd); // "group1"
            String filePath = url1.substring(groupEnd + 1);
            fastDfsUtil.delete_file(group,filePath);

            byte[] bytes = file.getBytes();
//            获取文件类型
            String filename = file.getOriginalFilename();
            String substring = filename.substring(filename.lastIndexOf(".")+1);
//            获取路径
            String url2 = fastDfsUtil.upload_file(bytes,substring);
//            将新的地址赋给新数据
            newTbContent.setPic(url2);
        }
//        根据id替换数据库数据
        tbContentService.updateContent(newTbContent);
        return "成功";
    }

    @RequestMapping("/getByStatus")
    @ResponseBody
    public List<TbContent> getByStatus(){
        return tbContentService.getContentByStatus();
    }
}
